﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using olierFrm.WebFormDev.Session;
using olierFrm.DataBase.FrameWork.StdQuery;

namespace olierFrm.WebFormDev.StdQuery
{
    public class StdQuery
    {
        public static string QueryName { get { return HttpContext.Current.Request.QueryString["QueryName"]; } }
        public static string ModuleID { get { return HttpContext.Current.Request.QueryString["ModuleID"]; } }


        /// <summary>
        /// 
        /// </summary>
        public class Session
        {
            public static void InitGridSession()
            {
                if (!SGrid.HaveQueryName(QueryName))
                {
                    var dbStdQuery = new StdQuerySQL(QueryName);
                    List<string> gfs = new List<string>();
                    if (dbStdQuery.StdQuery.GroupFields != null && dbStdQuery.StdQuery.GroupFields != "")
                    {

                        SGrid.AddGroup(dbStdQuery.StdQuery.QueryName,
                            dbStdQuery.StdQuery.GroupFields.Split(';').ToList());
                    }
                    SGrid.AddQueryName(QueryName);
                }
            }
        }


        /*
        public class Chart
        {

            DataTable dtSource = null;
            StdQuerySQL dbStdQuery = null;
            string DataSourceID = "";
            /// <summary>
            /// 实例化时，只生成控件，如果StdQuery有Chart时则会加到PageControlGridAndChart否则PageControlGridAndChart.Count=0
            /// </summary>
            /// <param name="dbStdQuery"></param>
            public Chart(StdQuerySQL dbStdQuery)
            {
                //是否开启图表
                if ((dbStdQuery.StdQuery.Property & 8) == 8)
                {
                    dbStdQuery.StdQuery.InCharts = "";
                }

                this.dbStdQuery = dbStdQuery;

                LoadChart();
            }

            /// <summary>
            /// 把数据绑定到图表控件
            /// </summary>
            /// <param name="dtSource"></param>
            public void DataBindToChart(DataTable dtSource, string dataSourceID)
            {
                this.dtSource = dtSource;
                DataSourceID = dataSourceID;
            }

            void paperChart_PageIndexChanging(object source, PagerPageEventArgs e)
            {
                var chartControl = (WebChartControl)PageControlChart.ActiveTabPage.Controls[0];
                BindChartControl(chartControl, (ASPxPager)PageControlChart.ActiveTabPage.Controls[1], e.NewPageIndex, ((ASPxPager)source).Attributes["Text"]);
            }
            void tabGridAndChart_ActiveTabChanged(object source, TabControlEventArgs e)
            {
                //try
                //{
                if (DataSourceID == "" || e.Tab.Controls[0].GetType().Name != "WebChartControl") return;
                var chartControl = (WebChartControl)e.Tab.Controls[0];
                BindChartControl(chartControl, (ASPxPager)e.Tab.Controls[1], 0, e.Tab.Text);
                //}
                //catch { }

            }

            private void BindChartControl(WebChartControl chartControl, ASPxPager paper, int pageIndex, string text)
            {
                chartControl.Series.Clear();
           
                InChart dbInChart = new InChart(new StdQuerySQL(dtSource.TableName).StdQuery.InCharts);
                var ix = dbInChart.SciptObject.Where(so => so.Key == text).First();

                int VisibleItem = ix.Value.VisibleItem != null && ix.Value.VisibleItem != "0" ?
                    Convert.ToInt32(ix.Value.VisibleItem) : 10;

                var dtFilter = dtSource.SelectToDataTable(
                    string.Format(dtSource.GetDataRowIndexFieldName() + " >= {0} and "
                    + dtSource.GetDataRowIndexFieldName() + " < {1}",
                    pageIndex * VisibleItem, (pageIndex + 1) * VisibleItem)
                    );

                chartControl.Width = 900;
                chartControl.Height = 400;
                var Field_Y = ix.Value.Field_Y.Split(';').ToList();
                Field_Y.Remove("");

                if (dtFilter.Columns[ix.Value.Field_X].DataType.Name.IndexOf("DateTime") != -1)
                {
                    if (!dtFilter.Columns.Contains(ix.Value.Field_X + "_N"))
                    {
                        dtFilter.Columns.Add(new DataColumn() { DataType = Type.GetType("System.String"), ColumnName = ix.Value.Field_X + "_N" });
                        for (int i = 0; i < dtFilter.Rows.Count; i++)
                        {
                            dtFilter.Rows[i][ix.Value.Field_X + "_N"] = DateTime.Parse(dtFilter.Rows[i][ix.Value.Field_X].ToString()).ToString("yyyy-MM-dd");
                        }
                    }
                    ix.Value.Field_X += "_N";
                }
                //ix.Value.ChartType = "1";
                foreach (var f in Field_Y)
                {
                    Series series = null;
                    switch (ix.Value.ChartType)
                    {
                        case "0":
                            series = new Series(f, ViewType.Bar);
                            break;
                        case "1":
                            series = new Series(f, ViewType.Point);
                            break;
                        case "2":
                            series = new Series(f, ViewType.Line);
                            break;
                        case "3":
                            series = new Series(f, ViewType.Area);
                            break;
                        case "4":
                            series = new Series(f, ViewType.Pie);
                            series.LegendText = f;
                            series.ShowInLegend = true;

                            series.PointOptions.PointView = PointView.ArgumentAndValues;
                            series.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
                            //series.PointOptions.ValueNumericOptions.Precision = 0;

                            PieSeriesView myView = (PieSeriesView)series.View;
                            myView.HeightToWidthRatio = 90;
                            myView.Titles.Add(new SeriesTitle() { Text = f });
                            ((PieSeriesLabel)series.Label).Visible = false;

                            break;
                    }

                    series.DataSource = dtFilter;
                    series.LegendPointOptions.ArgumentDateTimeOptions.FormatString = "yyyy-MM-dd";

                    series.PointOptions.ArgumentDateTimeOptions.FormatString = "yyyy-MM-dd";
                    series.ArgumentDataMember = ix.Value.Field_X;//X轴的数据字段
                    series.ValueDataMembers[0] = f;//Y轴的数据字段
                    chartControl.Series.Add(series);
                }


                paper.ItemCount = dtSource.Rows.Count;
            }
            public ASPxPageControl PageControlChart = new ASPxPageControl();

            private void LoadChart()
            {
                if (dbStdQuery.StdQuery.InCharts != null && dbStdQuery.StdQuery.InCharts.Trim().Length != 0)
                {
                    InChart ic = new InChart(dbStdQuery.StdQuery.InCharts);
                    //PageControlChart.AutoPostBack = true;
                    //PageControlChart.ActiveTabChanged += new TabControlEventHandler(tabGridAndChart_ActiveTabChanged);
                    int index = 0;
                    foreach (var i in ic.SciptObject)
                    {
                        var tpChart = new TabPage();
                        tpChart.Text = i.Key;
                        //WebChartControl chartControl = new WebChartControl();
                        tpChart.Controls.Add(new LiteralControl("<iframe class='iFrameChart' style='width:100%; height:355px;' frameborder='no' framespacing='0' border='0' url='Chart.aspx" + HttpContext.Current.Request.Url.Query + "&_Chart=" + index++ + "' src=''></iframe>"));
                        //tpChart.Controls.Add(chartControl);

                        //ASPxPager paperChart = new ASPxPager();
                        //paperChart.Attributes.Add("Text", i.Key);
                        //paperChart.PageIndexChanging += new PagerPageEventHandler(paperChart_PageIndexChanging);

                        //tpChart.Controls.Add(paperChart);

                        PageControlChart.TabPages.Add(tpChart);
                        
                    }
                    PageControlChart.ClientSideEvents.TabClick = "function(s,e){if (e.tab.index!=0){" +
                        "var iframe=$(s.mainElement).find(\"tbody > tr:eq(1) > td > div:eq(\"+e.tab.index+\") > iframe\");" +
                        "if (iframe.attr(\"url\")){iframe.attr(\"src\",iframe.attr(\"url\"));iframe.removeAttr(\"url\");}" +
                        "}}";
                }
            }
        }
        */


    }
}
